<template>
	<view class="content">
		<view style="width: 92%; margin: 18rpx auto">
			<u-search
				placeholder="请输入搜索的商品"
				v-model="goodsName"
				bgColor="#fff"
				@search="searchGoodsList"
				@custom="searchGoodsList"
			></u-search>
		</view>
		<view class="classify" v-if="!temState">
			<!-- 分类部分 -->
			<view class="cate-left">
				<view
					:class="['cate-item', activeIndex == index ? 'active' : '']"
					:style="{ color: activeIndex == index ? templateConfig.page.themeColor : '' }"
					v-for="(item, index) in categoryList"
					:key="index"
					@click="changeActive(item, index)"
				>
					{{ item.categoryName }}
					<view
						class="back"
						:style="{ background: activeIndex == index ? templateConfig.page.themeColor : '' }"
					></view>
				</view>
			</view>
			<view class="cate-right">
				<view class="scrollContainer" v-if="categoryXiaList.length>0">
					<scroll-view class="scrollView" scroll-x :scroll-left='scrollLeft' @scroll="scrollEvt">
						<view
							class="scrollitem"
							v-for="(item, index) in categoryXiaList"
							:key="index"
							@click="getItem(item, index)"
						>
							<view
								class="recommandItemText"
								:style="{
									color: activeIndex1 == index ? templateConfig.page.themeColor : '',
									color: activeIndex1 == index ? templateConfig.page.themeColor : '',
									background: activeIndex1 == index ? getRgb(templateConfig.page.themeColor, 0.1) : ''
								}"
							>
								{{ item.categoryName }}
							</view>
						</view>
					</scroll-view>
					<view class="icon">
						<u-icon
							name="arrow-right"
							:color="templateConfig.page.themeColor"
							size="24"
							@click="scrollLeftBtn()"
						></u-icon>
					</view>
					
				</view>

				<scroll-view scroll-with-animation scroll-y="true" class="right-aside" @scrolltolower="asideScroll"
				  :scroll-top='scrollTop' @scroll="scrollEvt1"
				 >
					<swiper
						class="swiper"
						:indicator-dots="false"
						:autoplay="true"
						:interval="10000"
						:duration="1000"
						@change="changeSwiper"
						:current="currentIndex"
						:style="{ height: swiperHeight + 'px' }"
						v-if="recommendedList.length > 0"
					>
						<swiper-item v-for="(item, index) in recommendedList" :key="index">
							<image
								class="swiper-img"
								:src="item.activityImgUrl"
								lazy-load="true"
								mode="widthFix"
								@load="loadImg"
							></image>
						</swiper-item>
					</swiper>
					<view class="cate-content" v-for="(item, index) in goodsList" :key="index" :data-index="index">
						<image
							class="cateImg"
							:src="item.rotationImgsJson[0]"
							mode="aspectFit"
							@click="goodsItemClick(item)"
						></image>
						<view class="conten-right">
							<view class="goodsname" @click="goodsItemClick(item)">
								{{ item.goodsName }}
							</view>
							<view class="goodsprice">
								<view
									class="price"
									:style="{ color: templateConfig.page.themeColor }"
									@click="goodsItemClick(item)"
								>
									<view>
										<text>￥</text>
										<text class="price-text" v-if="item.goodsSpecificationList == null">
											{{ item.goodsPrice }}
										</text>
										<text class="price-text" v-else>
											{{ item.goodsSpecificationList[0].dealPrice }}
										</text>
									</view>
									<view class="old-price" v-if="item.scribePrice > 0">￥{{ item.scribePrice }}</view>
								</view>
								<u-icon
									name="shopping-cart"
									:color="templateConfig.page.themeColor"
									size="28"
									@click.stop="addToCart(item)"
								></u-icon>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
			<tabbar
				:current="1"
				:cart="cartNums"
				:template="templateConfig"
				:tabbarList="templateConfig.tabbarList"
			></tabbar>
		</view>
		<view class="" v-else>
			<expire></expire>
		</view>
	</view>
</template>

<script>
import {
	getPlugsShopCartByUserId,
	getBusinessInfoList,
	getRecommen,
	getHomeDataInfo,
	getCategory,
	insertPlugsShopCart,
	searchPlugsGoodsByCategoryId,
	searchPlugsGoodsSpecificationByGoodsId
} from '../../static/utils/api.js';
import { getRgb } from '../../static/utils/utils.js';
export default {
	data() {
		return {
			templateConfig: uni.getStorageSync('templateConfig'),
			temState: uni.getStorageSync('templateExpireTime'),
			cartNums: 0,
			activeIndex: 0,
			categoryList: [],
			goodsList: [],
			recommendedList: [],
			categoryId: -1,
			total: 0,
			page: 1,
			categoryXiaList: [],
			pid: 0,
			activeIndex1: 0,
			goodsName: '',
			currentIndex: 0,
			swiperHeight: 0,
			rightHeight: 0,
			scrollTop:0,
			scrollLeft:0
		};
	},

	onLoad() {
		this.nowBusinessInfo = uni.getStorageSync('nowBusinessInfo');
		this.getCategoryList();
	},
	onShow() {
		this.getCartList();
		uni.setNavigationBarTitle({
			title: this.templateConfig.tabbarList[1].iconName
		});
		if (this.nowBusinessInfo.businessName != uni.getStorageSync('nowBusinessInfo').businessName) {
			this.nowBusinessInfo = uni.getStorageSync('nowBusinessInfo');
			this.getCategoryList();
			this.page = 1;
			this.goodsList = [];
			this.activeIndex = 0;
			this.activeIndex1 = 0;
			this.getCartList();
			this.getswiperList();
		} else {
			this.nowBusinessInfo = uni.getStorageSync('nowBusinessInfo');
			this.getswiperList();
			this.getCartList();
		}
	},
	onReachBottom() {},
	methods: {
		getRgb,
		scrollLeftBtn(){
			this.scrollLeft+=20
		},
		scrollEvt(e){
			this.$nextTick(()=>{
				this.scrollLeft=e.detail.scrollLeft
			})
		},
		scrollEvt1(e){
			this.$nextTick(()=>{
				// this.scrollTop=e.detail.scrollTop
			})
		},
		// 获取一级分类
		getCategoryList() {
			let data = {
				businessId: this.nowBusinessInfo.businessId.toString(),
				pid: 0
			};
			getCategory(data).then((res) => {
				if (res.code == 200) {
					this.categoryList = res.body.list;
					this.pid = this.categoryList[0].id.toString();
					this.getCategoryTwoList();
				}
			});
		},

		// 获取二级分类
		getCategoryTwoList() {
			let data = {
				businessId: this.nowBusinessInfo.businessId.toString(),
				pid: this.pid
			};
			getCategory(data).then((res) => {
				if (res.code == 200) {
					if (res.body.list.length > 0) {
						this.categoryXiaList = res.body.list;
						this.categoryId = this.categoryXiaList[0].id.toString();
						this.getGoodlist();
					} else {
						this.categoryXiaList = [];
						this.categoryId = this.pid;
						this.getGoodlist();
					}
				}
			});
		},
		// 切换一级分类
		changeActive(item, index) {
			this.pid = item.id.toString();
			this.scrollTop=0
			this.scrollLeft=0
			this.$nextTick(()=>{
				this.scrollTop+=10
				this.scrollLeft+=1
			})
			this.page = 1;
			this.activeIndex = index;
			this.activeIndex1 = 0;
			this.goodsList = [];
			this.getCategoryTwoList();
			
		},
		// 切换二级分类
		getItem(item, index) {
			this.scrollTop=0
			this.$nextTick(()=>{
				this.scrollTop+=10
			})
			this.page = 1;
			this.activeIndex1 = index;
			this.categoryId = item.id.toString();
			this.getGoodlist();
		},
		searchGoodsList() {
			this.page = 1;
			this.goodsList = [];
			this.getGoodlist();
		},
		// 获取商品
		getGoodlist() {
			uni.showLoading({
				title: '加载数据中',
				mask: true
			});
			let data = {
				page: this.page,
				businessId: this.nowBusinessInfo.businessId.toString(),
				categoryId: this.categoryId.toString(),
				goodsName: this.goodsName
			};
			console.log(data, 234);
			searchPlugsGoodsByCategoryId(data).then((res) => {
				if (res.code == 200) {
					if (this.page == 1) {
						this.goodsList = [];
					}
					res.body.list.forEach((item) => {
						if (item.rotationImgsJson) {
							item.rotationImgsJson = JSON.parse(item.rotationImgsJson);
						}
					});
					let arr = [];
					arr = this.goodsList.concat(res.body.list);
					this.goodsList = arr;
					uni.hideLoading();
					this.total = res.body.total;
				}
			});
		},
		// 滚动加载页面
		asideScroll() {
			console.log(this.goodsList.length, this.total);
			if (this.goodsList.length < this.total) {
				this.page++;
				this.getGoodlist();
			}
		},

		// 获取轮播
		getswiperList() {
			let postdata = {
				businessId: this.nowBusinessInfo.businessId.toString()
			};
			getRecommen(postdata).then((res) => {
				if (res.code == 200) {
					let arr1 = [];
					arr1 = res.body.filter((itm) => itm.type === 'categoryData');
					this.recommendedList = arr1;
				}
			});
		},
		
		loadImg() {
			this.setSwiperHeight('.swiper-img');
		},
		
		changeSwiper(e) {
			this.currentIndex = e.detail.current;
			//动态设置swiper的高度，使用nextTick延时设置
			this.$nextTick(() => {
				this.setSwiperHeight('.swiper-img');
			});
		},
		// 获取轮播高度
		setSwiperHeight(element) {
			console.log(99999);
			let query = uni.createSelectorQuery().in(this);
			query.selectAll(element).boundingClientRect();
			query.exec((res) => {
				if (this.recommendedList.length && res[0][this.currentIndex].height) {
					this.swiperHeight = res[0][this.currentIndex].height;
				}
			});
		},
		// 获取购物车
		getCartList() {
			let data = {
				page: 1,
				size: 100,
				businessId: this.nowBusinessInfo.businessId.toString(),
				userServiceToken: this.userToken
			};
			getPlugsShopCartByUserId(data).then((res) => {
				if (res.code === 200) {
					this.cartNums = res.body.total;
					uni.setStorageSync('goodsNum', this.cartNums);
				}
			});
		},
		// 加入购物车
		addToCart(item) {
			let token = uni.getStorageSync('userInfo').accessToken;

			if (token == null) {
				uni.showModal({
					title: '提示',
					content: '登录才能添加宝贝哦~',
					success: function (res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/user/login'
							});
						} else if (res.cancel) {
						}
					}
				});
			} else {
				searchPlugsGoodsSpecificationByGoodsId({
					goodsId: item.id
				}).then((res) => {
					if (res.code == 200) {
						if (res.body.plugsGoodsSpecificationList.length == 0) {
							let postData = {
								businessId: this.nowBusinessInfo.businessId.toString(),
								goodsId: item.id,
								goodsCategoryId: item.categoryId,
								goodsNum: 1,
								goodsSpecificationIds: '0'
							};
							if (item.stockNum <= 0) {
								uni.showModal({
									title: '提示',
									content: '库存不足!',
									showCancel: false
								});
								return;
							}
							item.stockNum--;
							insertPlugsShopCart(postData).then((res) => {
								if (res.code == 200) {
									uni.showToast({
										title: '加入成功',
										icon: 'none'
									});
									this.getCartList();
								} else {
									item.stockNum++;
								}
							});
						} else {
							let postData = {
								businessId: this.nowBusinessInfo.businessId.toString(),
								goodsId: item.id,
								goodsCategoryId: item.categoryId,
								goodsNum: 1,
								goodsSpecificationIds: res.body.plugsGoodsSpecificationList[0].id
							};
							if (res.body.plugsGoodsSpecificationList[0].stockNum <= 0) {
								uni.showModal({
									title: '提示',
									content: '库存不足!',
									showCancel: false
								});
								return;
							}
							res.body.plugsGoodsSpecificationList[0].stockNum--;
							insertPlugsShopCart(postData).then((res) => {
								if (res.code == 200) {
									uni.showToast({
										title: '加入成功',
										icon: 'none'
									});
									this.getCartList();
								} else {
									res.body.plugsGoodsSpecificationList[0].stockNum++;
								}
							});
						}
					}
				});
			}
		},
		goodsItemClick(item) {
			uni.navigateTo({
				url: `/pages/index/detail?id=${item.id}`
			});
		}
	}
};
</script>

<style lang="scss">
.classify {
	background-color: #fff;
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: space-between;
	height: 80vh;
	.cate-left {
		width: 280rpx;
		height: 80vh;
		overflow: auto;
		background-color: #f6f6f6;
		.cate-item {
			width: 100%;
			height: 100rpx;
			line-height: 100rpx;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
			padding-left: 30rpx;
			box-sizing: border-box;
			position: relative;
		}
		.back {
			width: 5rpx;
			border-radius: 6rpx;
			height: 50rpx;
			background-color: #ffff;
			position: absolute;
			left: 5rpx;
			top: 30rpx;
		}
		.active {
			background-color: #ffffff;
			padding-left: 30rpx;
			color: #ff5d32;
			font-weight: 700;
			box-sizing: border-box;
		}
	}

	.cate-right {
		width: 100%;
		height: 80vh;
		box-sizing: border-box;
		padding: 0rpx 20rpx;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		// 二级分类
		.scrollContainer {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 0 10rpx;
			.scrollView{
				width: 88%;
				background-color: #fff;
				white-space: nowrap;
				height: 60rpx;
				.scrollitem {
					display: inline-block;
					margin-right: 20rpx;
					.recommandItemText {
						height: 60rpx;
						line-height: 60rpx;
						text-align: center;
						padding: 0rpx 20rpx;
						color: #666666;
						font-size: 24rpx;
						border-radius: 5rpx;
						background: #edeff2;
						text-overflow: ellipsis;
						overflow: hidden;
						white-space: nowrap;
					}
				}
			}
			.icon{
				
			}
			
		}
		.right-aside {
			flex: 1;
			padding:10rpx 0 30rpx;
			overflow: hidden;
			.swiper {
				margin: 10rpx 0 20rpx;
				.swiper-img {
					border-radius: 10rpx;
				}
			}
			
			.cate-content {
				width: 100%;
				height: 160rpx;
				margin-bottom: 20rpx;
				padding-bottom: 20rpx;
				display: flex;
				border-bottom: 2rpx solid #e9e9e9;
				.cateImg {
					width: 160rpx;
					height: 160rpx;
					border-radius: 16rpx;
				}
				
				.conten-right {
					flex:1;
					height: 100%;
					display: flex;
					box-sizing: border-box;
					flex-direction: column;
					justify-content: space-between;
					padding: 0rpx 30rpx;
				}
			
				.goodsname {
					width: 100%;
					font-size: 30rpx;
					display: -webkit-box; //将对象作为弹性伸缩盒子模型显示
					-webkit-box-orient: vertical; //设置或检索伸缩盒对象的子元素的排列方式
					-webkit-line-clamp: 2; //一个块元素显示的文本的行数
					overflow: hidden; //溢出隐藏
					
				}
			
				.goodsprice {
					width: 100%;
					box-sizing: border-box;
					display: flex;
					justify-content: space-between;
					align-items: center;
			
					.price {
						color: #ff4544;
						display: flex;
						align-items: center;
			
						.price-text {
							font-size: 34rpx;
							font-weight: 600;
						}
			
						.old-price {
							color: #93a1a1;
							font-size: 24rpx;
							margin-left: 16rpx;
							text-decoration: line-through;
						}
					}
			
				}
			
				
			}
			
		}

		
	}
}
</style>
